/**
 * eknows base components
 *
 * Copyright Leon
 * Date 2017-08-30
 */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {
		define([
			"jquery",
			"jquery.slimscroll",
			"jquery.color",
			"./core",
			"./component"
		], factory );
	} else {
		factory( jQuery );
	}
}(function( $ ) {
	
var slideClass = "eknows-menu-slide", logoClass = "eknows-menu-logo", contentClass = "eknows-menu-content", pMenuClass = "eknows-menu", cMenuClass = "eknows-menu-sub", openClass = "eknows-menu-open", hoverClass = "eknows-menu-hover",
	suffixIconClass = "eknows-menu-suffixicon", suffixIconClass1 = "eknows-menu-suffixicon-1";
var menuLeftIconClass = "eknowsicon-menu-right", menuDownIconClass = "eknowsicon-menu-down", menuSlideIconClass = "glyphicon-align-justify";
	
$.component("eknows.eknowsmenu", {
	version : "1.0.0",
	defaultElement : "<div>",
	
	_curStatus: 0, //菜单当前状态
	
	options: {
		disabled: null,
        width: 0,	//菜单宽度
        logo: "",   //企业logo
		
		openIdx: -1, //菜单默认展开项，-1不展开
		pName: [
		  //菜单名1，菜单名2，菜单名3...
		],
		pId: [
		  //编号1，编号2，编号3...    
		],
		pIcon: [
		  //图标1，图标2，图标3...      
		],
		pUrl: [
		  //跳转地址1，跳转地址2，跳转地址3...     
        ],
        permissionUrl: [
          //权限1，权限2，权限3...
        ],
		cList: [
		  //子菜单
		  //{id: 1, title: "子菜单", url: "子菜单url", groupId: 1}      
		],
		menuClick: null,	//菜单点击回调函数
		
		//滑动块配置
		isSlide: false,	//是否启用菜单滑动
		slideOpen: null,	//菜单展开回调函数
		slideClose: null	//菜单关闭回调函数
	},
	
	//默认创建函数
	_create: function() {
		var _this = this;
		
		if (typeof _this.options.disabled != "boolean") {
			_this.options.disabled = !!_this.element.prop("disabled");
		} else {
			_this.element.prop("disabled", _this.options.disabled);
		}
		
		var menuContainer = _this._createContainer();

        if (_this.options.pName && _this.options.pName.length > 0) {
            _this._createItem(menuContainer);
        }
        _this.element.append(menuContainer).addClass(pMenuClass);

        if (_this.options.logo !== "") {
            var logoContainer = _this._createLogo();
            _this.element.prepend(logoContainer);
        }

        if (_this.options.isSlide === true) {
            var slideContainer = _this._createSlide();
            _this.element.prepend(slideContainer);
        }

        //设置样式
        _this._changeStyle();

        //如果菜单是默认值，窗口改变则改变菜单大小
        $(window).resize(function () {
            var wrapDiv = _this.element.find("." + contentClass).parent();
            _this.element.append(_this.element.find("." + contentClass));
            wrapDiv.remove();

            _this._changeStyle();
        });
	},
	
	//创建菜单内容容器
	_createContainer: function () {
        var menuContainer = $("<ul></ul>").addClass(contentClass);

        return menuContainer;
    },

    //创建企业LOGO
    _createLogo: function () {
        var _this = this, logoContainer = $("<div></div>").addClass(logoClass); 

        logoContainer.append($("<img></img>").attr("src", _this.options.logo));

        return logoContainer;
    },
    
    //创建滑动区域
    _createSlide: function () {
        var _this = this, slideContainer = $("<div></div>").addClass(slideClass);

        slideContainer.on("click" + _this.eventNamespace, function() {
                _this._slideClick.apply(_this, arguments);
            });

        return slideContainer;
    },
    
    //创建菜单项
    _createItem: function (menuContainer) {
        var _this = this, openItem;

        for (var i = 0, menuSize = _this.options.pName.length; i < menuSize; i++) {
            var pIcon = $("<span></span>").addClass(this.options.baseIconClass + " " + _this.options.pIcon[i]);	//父菜单图标
            var sIcon = $("<span></span>").addClass(this.options.baseIconClass + " " + menuLeftIconClass + " " + suffixIconClass);	//子菜单图标
            var link = $("<a></a>").append(pIcon).append("<span>" + _this.options.pName[i] + "</span>");

            if (_this.options.pUrl[i] === "" || !_this.options.pUrl[i]) {
                link.append(sIcon);
            }
            link.data("mid", _this.options.pId[i]);
            var list = $("<li></li>").append(link);

            //添加权限
            if (_this.options.permissionUrl[i] !== "") {
                list.attr("permissionUrl", _this.options.permissionUrl[i]);
            }

            menuContainer.append(list);

            if (_this.options.pUrl[i] !== "") {
                //能直接打开的菜单无子级菜单
                link.attr("href", _this.options.pUrl[i]);

                if (_this.options.menuClick) {
                	
                	link.on("click" + _this.eventNamespace, 
                			function (e) {
		                        e.preventDefault();
		
		                        _this.options.menuClick.apply(_this, arguments);
		
		                        return false;
                            });
                    link.hover(
                        function() {
                            $(this).addClass(hoverClass);
                        },
                        function() {
                            $(this).removeClass(hoverClass);
                        });                   
                }
            } else {
                var childContainer = $("<ul></ul>");
                list.addClass(cMenuClass).append(childContainer);
                //父菜单点击事件
                link.on("click" + _this.eventNamespace,
                		function() {
                			_this._itemClick.apply(_this, arguments);
                        });
                //父菜单覆盖事件
                link.hover(
                    function() {
                        $(this).addClass(hoverClass);
                    },
                    function() {
                        $(this).removeClass(hoverClass);
                    });

                if (_this.options.pId[i] == _this.options.openIdx) {
                    openItem = link;
                }

                //建立子菜单
                for (var j = 0, childSize = _this.options.cList.length; j < childSize; j++) {
                    if (_this.options.cList[j].groupId == _this.options.pId[i]) {
                        var slink = $("<a></a>").append(_this.options.cList[j].title).attr("href", _this.options.cList[j].url).data("mid", _this.options.cList[j].id);;
                        var slist = $("<li></li>").append(slink);

                        //添加子菜单权限
                        if (_this.options.cList[j].permissionUrl !== "") {
                            slink.attr("permissionUrl", _this.options.cList[j].permissionUrl);
                        }

                        if (_this.options.menuClick) {
                            slink.on("click" + _this.eventNamespace, 
                        			function (e) {
        		                        e.preventDefault();
        		
        		                        _this.options.menuClick.apply(_this, arguments);
        		
        		                        return false;
        		                    });
                        }

                        childContainer.append(slist);
                    }
                }
            }
        }

        if (openItem) {
            var sMenu = openItem.siblings("ul"),
				pItem = openItem.parent();

            openItem.find("." + suffixIconClass).removeClass(menuLeftIconClass).addClass(menuDownIconClass);
            openItem.parent().addClass(openClass);

            sMenu.slideDown();
        }
    },
    
    _changeStyle: function () {
    	var _this = this;
    	
        //设置自定义菜单宽度
        if (_this.options.width !== 0) {
        	_this.element.css("width", _this.options.width);
            _this.element.find("." + contentClass).css("width", _this.options.width);
            _this.element.find("." + logoClass).css("width", _this.options.width);
        }
        //设置菜单高度为窗口高度
        var sHeight = $(window).height();

        _this.element.find("." + contentClass).slimScroll({
            width: _this.options.width,
            height: sHeight - parseInt(_this.element.find("." + logoClass).css("height")),
            borderRadius: 0,
            railBorderRadius: 0
        });
    },

    /**
	 * 菜单点击处理
	 */
    _itemClick: function (e) {
        e.preventDefault();

        var _this = this /** UI对象 */, link = e.currentTarget /** 点击的菜单对象 */;
        var sMenu = $(link).siblings("ul"),
            pItem = $(link).parents("li"),
			sMenuList = _this.element.find("li." + cMenuClass + " ul"),
			pMenuList = _this.element.find("li." + cMenuClass);

        if (pItem.hasClass(openClass)) {
            sMenu.slideUp();

            pItem.removeClass(openClass);
            $(link).find("." + suffixIconClass).removeClass(menuDownIconClass).addClass(menuLeftIconClass);

            _this.options.openIdx = -1;
        } else {
            sMenuList.slideUp();
            sMenu.slideDown();

            pMenuList.removeClass(openClass);
            pMenuList.children("a").each(function (index, elem) {
                var iconItem = $(elem).find("." + suffixIconClass);
               
                if (iconItem.hasClass(menuDownIconClass)) {
                    iconItem.removeClass(menuDownIconClass).addClass(menuLeftIconClass);
                }
            });

            pItem.addClass(openClass);
            $(link).find("." + suffixIconClass).removeClass(menuLeftIconClass).addClass(menuDownIconClass);

            //设置正确的openIdx值
            _this.element.find("." + contentClass).children("li").each(function (index, elem) {
                if ($(elem).hasClass(openClass)) {
                    _this.options.openIdx = _this.options.pId[index];
                }
            });
        }
        
        return false;
    },

    /**
	 * 滑动块点击
	 */
    _slideClick: function (e) {
        var _this = this,
        	listItem = _this.element.find("." + contentClass).children("li");

        if (_this._curStatus === 0) {
        	//当前展开状态，点击收缩菜单
            listItem.each(function (index, elem) {
                var link = $(elem).children("a");

                //取消菜单项原绑定事件，添加新事件（点击后展开菜单）
                link.off("click");
                link.on("click" + _this.eventNamespace, function(e) {
                			e.preventDefault();
                			
                			_this._slideClick.apply(_this, arguments);
                			
                			return false;
                        });
            });

            _this._clearExpandStatus();
            _this.element.animate({ "left": -(_this.options.width - 54) }, 400, function() {
                if (_this.options.slideClose) {
                    _this.options.slideClose.apply(_this);
                }
            });

            _this._curStatus = 1;
        } else if (_this._curStatus == 1) {
            listItem.each(function (index, element) {
                var link = $(element).children("a");

                link.off("click");
                
                if (link.attr("href") === "" || link.attr("href") === undefined) {
                	link.on("click" + _this.eventNamespace,
                    		function() {
                    			_this._itemClick.apply(_this, arguments);
                    		});
                } else {
                    if (_this.options.menuClick) {
                    	link.on("click" + _this.eventNamespace, 
                    			function (e) {
    		                        e.preventDefault();
    		
    		                        _this.options.menuClick.apply(_this, arguments);
    		
    		                        return false;
    		                    });
                    }
                }
            });

            _this._resetExpandStatus();
            _this.element.animate({ "left": 0 }, 400, function() {
                if (_this.options.slideOpen) {
                    _this.options.slideOpen.apply(_this);
                }
            });

            _this._curStatus = 0;
        }
    },

    //折叠菜单时，要把菜单的展开状态清除
    _clearExpandStatus: function () {
        var _this = this,
        	openItem = _this.element.find("li." + openClass),
			linkList = _this.element.find("li." + cMenuClass).children("a");

        openItem.children("ul").slideUp();
        openItem.removeClass(openClass);

        //移除所有菜单指示图标
        linkList.children("." + suffixIconClass).remove();
        
        _this.element.find("." + contentClass).children("li").each(function (index, elem) {
            var icon = $(elem).find("span");
            icon.addClass("animated fadeIn");
            
            icon.addClass(suffixIconClass1);	//移动所有菜单图片适应菜单折叠状态

            $(elem).removeClass("animated fadeIn");
        });
    },

    //显示完整菜单时，要复原菜单的展开状态
    _resetExpandStatus: function () {
        var _this = this,
        	listItem = _this.element.find("." + contentClass).children("li");

        //移除菜单折叠状态图标样式
        listItem.addClass("animated fadeIn");
        listItem.find("span").removeClass(suffixIconClass1).removeClass("animated fadeIn");

        //还原菜单指示图标
        listItem.each(function (index, elem) {
            var link = $(elem).children("a");

            if (_this.options.pUrl[index] === "" || !_this.options.pUrl[index]) {
                var sIcon = $("<span></span>").addClass(_this.options.baseIconClass + " " + menuLeftIconClass + " " + suffixIconClass);
                link.append(sIcon);
            }
        });

        if (_this.options.openIdx == -1) {
            return;
        }

        for (var i = 0, len = _this.options.pId.length; i < len; i++) {
            if (_this.options.openIdx == _this.options.pId[i]) {
                break;
            }
        }

        if (_this.options.pUrl[i] !== "") {
            return;
        }

        var pItem = listItem.eq(i);
        var sMenu = pItem.find("ul");
        pItem.children("a").find("." + suffixIconClass).removeClass(menuLeftIconClass).addClass(menuDownIconClass);
        pItem.addClass(openClass);
        sMenu.slideDown();
    },
    
    isOpen: function () {
        var _this = this;
        return _this._curStatus == 0 ? true : false;
    }

});
	
}));